<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="60%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="题目类型" prop="optionType">
        <el-select
          v-model="formData.optionType"
          placeholder="请选择题目类型"
          clearable
          :disabled="formType === 'update'"
        >
          <el-option
            v-for="dict in optionTypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="题目内容" prop="questionContent">
        <el-input
          type="textarea"
          v-model.trim="formData.questionContent"
          maxlength="2000"
          placeholder="请输入题目内容"
        />
      </el-form-item>
      <el-form-item label="题目解析" prop="analysis">
        <el-input
          type="textarea"
          v-model.trim="formData.analysis"
          maxlength="2000"
          placeholder="请输入题目解析"
        />
      </el-form-item>
      <!-- 单选题和多选题的选项内容 -->
      <el-form-item
        label="选项内容"
        prop="optionList"
        v-if="formData.optionType === 1 || formData.optionType === 2"
      >
        <el-text type="danger">选项内容说明：选择题必须至少有一项答案内容。</el-text>
        <el-table :data="formData?.optionList" align="center" :row-key="(row) => row.id">
          <el-table-column label="序号" type="index" min-width="60" align="center" fixed>
            <template #default="{ $index }">
              <span>{{ $index }}</span>
            </template>
          </el-table-column>
          <el-table-column label="选项值" prop="optionKey" min-width="100" align="center">
            <template #default="{ $index }">
              <span>{{ String.fromCharCode(65 + $index) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="选项内容" prop="optionContent" min-width="110" align="center">
            <template #default="{ row, $index }">
              <el-form-item
                :prop="`optionList.${$index}.optionContent`"
                :rules="formRules.optionContent"
              >
                <el-input
                  v-model.trim="row.optionContent"
                  placeholder="请输入..."
                  type="textarea"
                  maxlength="2000"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="选项解析" prop="optionAnalysis" min-width="110" align="center">
            <template #default="{ row, $index }">
              <el-form-item :prop="`optionList.${$index}.optionAnalysis`">
                <el-input
                  v-model.trim="row.optionAnalysis"
                  placeholder="请输入..."
                  type="textarea"
                  :autosize="{ minRows: 1, maxRows: 4 }"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="operate" min-width="180" align="center">
            <template #default="{ $index }">
              <el-button
                :disabled="$index == 0"
                @click="onSortChange($index, $index - 1)"
                type="primary"
                >↑</el-button
              >
              <el-button
                :disabled="$index == formData.optionList.length - 1"
                @click="onSortChange($index, $index + 1)"
                type="primary"
                >↓</el-button
              >
              <el-button @click="onDeleteOption($index)" type="danger">-</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item v-if="formData.optionType === 1 || formData.optionType === 2">
        <div style="display: flex; width: 100%; justify-content: center">
          <el-button @click="onAddOption" type="primary">新增</el-button>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
const { t } = useI18n() // 国际化
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

const formData = ref({
  id: undefined,
  questionStatus: 1,
  optionType: undefined,
  judgeType: undefined,
  questionContent: undefined,
  analysis: undefined,
  optionList: [
    {
      optionSort: 0, // 选项排序
      optionKey: String.fromCharCode(65), // 选项key值
      optionContent: undefined, // 选项内容
      optionAnalysis: undefined // 选项解析
    }
  ]
})
const formRules = reactive({
  optionType: [{ required: true, message: '题目类型不能为空', trigger: 'change' }],
  questionContent: [{ required: true, message: '题目内容不能为空', trigger: 'blur' }],
  optionList: [{ required: true, message: '请填写选项内容', trigger: ['change', 'blur'] }],
  optionContent: [{ required: true, message: '请设置选项文本', trigger: ['change', 'blur'] }],
  optionKey: [{ required: true, message: '请设置选项值', trigger: ['change', 'blur'] }],
  questionStatus: [{ required: true, message: '题目状态不能为空', trigger: ['change', 'change'] }]
})
const formRef = ref() // 表单 Ref
const list = ref([]) //全部数据

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  const saved = window.localStorage.getItem('questionList')
  list.value = saved ? JSON.parse(saved) : []
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = list.value.find((obj) => obj.id === id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 重新设置排序[提交前排序一下]
  formData.value.optionList.forEach((item, index) => {
    item.optionSort = index
    item.optionKey = String.fromCharCode(65 + index)
  })
  if (formData.value.id) {
    list.value = replaceById(list.value, formData.value.id, formData.value)
  } else {
    formData.value.id = randomId10() //给一个id
    list.value.push(formData.value)
  }
  // 提交请求
  formLoading.value = true
  try {
    console.log('题目', formData.value)
    // 把题目存到store
    window.localStorage.setItem('questionList', JSON.stringify(list.value))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

//#region 选项排序
function onSortChange(oldIndex, newIndex) {
  const optionList = formData.value.optionList
  const item = optionList.splice(oldIndex, 1)[0]
  optionList.splice(newIndex, 0, item)
}
//#endregion

//#endregion 选项相关
function onAddOption() {
  if (formData.value.optionList == null) {
    formData.value.optionList = []
  }

  formData.value.optionList.push({
    optionSort: formData.value.optionList.length,
    optionContent: undefined,
    optionKey: String.fromCharCode(65 + formData.value.optionList.length),
    optionAnalysis: undefined
  })
}

function onDeleteOption(idx) {
  formData.value.optionList.splice(idx, 1)
}
//#endregion

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    questionStatus: 1,
    optionType: undefined,
    judgeType: undefined,
    questionContent: undefined,
    analysis: undefined,
    optionList: [
      {
        optionSort: 0, // 选项排序
        optionKey: String.fromCharCode(65), // 选项key值
        optionContent: undefined, // 选项内容
        optionAnalysis: undefined // 选项解析
      }
    ]
  }
  list.value = []
  formRef.value?.resetFields()
}

// 题目类型
const optionTypeList = reactive([
  { value: 1, label: '单选题' },
  { value: 2, label: '多选题' },
  { value: 3, label: '判断题' },
  { value: 4, label: '简答题' }
])

/**
 * 生成 10 位随机数字字符串（纯数字）
 * 例：4729385610
 */
function randomId10(): string {
  return String(Math.floor(Math.random() * 9_000_000_000) + 1_000_000_000)
}

/**
 * 按 id 精准替换数组中的某一项
 * 如果找到，就地替换并返回新数组；找不到原样返回
 */
function replaceById<T extends { id: string | number }>(
  list: T[],
  id: string | number,
  newData: Partial<T>
): T[] {
  return list.map((item) =>
    String(item.id) === String(id)
      ? { ...item, ...newData } // 合并老对象与新数据
      : item
  )
}
</script>
